export default {
  namespaced: true,
  state: {
    goodsCart: uni.getStorageSync('goodsCart') || []
  },
  getters: {
    // 过滤选中列表
    checkedCartList(state) {
      return state.goodsCart.filter(item => item.checked)
    },
    // 计算选中商品数量
    CartNum(state, getters) {
      return getters.checkedCartList.reduce((count, item) => count += item.nums, 0)
    },

    // 计算选中商品总价
    CartAllPrice(state, getters) {
      return getters.checkedCartList.reduce((price, item) => price += item.nums * item.goods_price, 0)
    }
  },
  mutations: {
    // payload 是商品详情
    addGoods(state, payload) {
      // 判断当前商品是否已存在
      const index = state.goodsCart.findIndex(item => item.goods_id === payload.goods_id)
      if (index === -1) {
        // 不存在 push新的元素
        // 要自己设置一个购买数量进去
        state.goodsCart.push({ ...payload, nums: 1, checked: true })
      } else {
        // 存在
        // 存在 找到它 购买数量 ++
        state.goodsCart[index].nums++
      }
      uni.setStorageSync('goodsCart', state.goodsCart)
    },
    // 商品的选中 取反功能 payload = {index}
    cartGoodsChecked(state, payload) {
      state.goodsCart[payload.index].checked = !state.goodsCart[payload.index].checked
      uni.setStorageSync('goodsCart', state.goodsCart)
    },
    // 数量编辑 增payload = {unit:1,index} 减payload={unit:-1,index}
    cartGoodsNumberUpdate(state, payload) {
      state.goodsCart[payload.index].nums += payload.unit
      uni.setStorageSync('goodsCart', state.goodsCart)
    },
    // 移除购物车
    cartGoodsRemove(state, payload) {
      // 删除数组的的某个元素，即是删除购物车某项，通过下标删除
      state.goodsCart.splice(payload.index, 1)
      uni.setStorageSync('goodsCart', state.goodsCart)
    },
    // 修改单选 checked
    cartGoodsAllChecked(state, payload) {
      state.goodsCart.forEach(item => item.checked = payload.checked);
      uni.setStorageSync('goodsCart', state.goodsCart)
    }
  },
  actions: {

  }
}